package 链表;

import common.ListNode;

import java.util.List;

/**
 * @author tmh
 * @date 2024/11/22 19:37
 * @description
 */
public class T19删除链表的倒数第N个结点 {
    public static void main(String[] args) {
        ListNode node = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,new ListNode(4,
                                new ListNode(5)))));
        removeNthFromEnd(node,2);
    }
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre = new ListNode();
        pre.next=head;
        int len=0;
        while (head!=null){
            len++;
            head=head.next;
        }
        head=pre;
        //这里是需要虚拟节点的，因为i一开始为0的时候，head就指向第二个节点了
        for (int i=0;i<len-n;i++){
            head=head.next;
        }
        head.next=head.next.next;
        return pre.next;
    }
}
